package com.cy.pj.sys.service.impl;
import com.cy.pj.common.exception.ServiceException;
import com.cy.pj.common.pojo.CheckBox;
import com.cy.pj.common.pojo.PageObject;
import com.cy.pj.sys.dao.SysUserDao;
import com.cy.pj.sys.dao.SysUserRoleDao;
import com.cy.pj.sys.pojo.SysLog;
import com.cy.pj.sys.pojo.SysUser;

import com.cy.pj.sys.service.SysUserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserDao sysUserDao;

    @Override
    public PageObject<SysUser> findPageObjects
            (String username, Integer pageCurrent) {

        int pageSize=4;//页面大小，每页最多显示多少条记录
        Page<SysUser> page= PageHelper.startPage(pageCurrent, pageSize);
        List<SysUser> records=
                sysUserDao.findPageObjects(username);
        //4.封装查询结果
        return new PageObject
                ( (int)page.getTotal(), records, pageSize,pageCurrent);
    }


    @Override
    //添加禁用启用方法,关键代码如下:
    public int validById(Integer id, Integer valid) {
        int rows=sysUserDao.validById(id,valid);
        if(rows==0)throw new ServiceException("记录可能已经不存在");
        return rows;
    }
    @Autowired
    private SysUserRoleDao sysUserRoleDao;
    @Override
    public int saveObject(SysUser entity, Integer[] roleIds) {
        //参数校验(省略)
    //产生一个随机字符串作为加密盐使用
        String salt= UUID.randomUUID().toString();
    //对密码进行MD5盐值加密(MD5特点:不可逆,相同内容加密结果也相同)
        SimpleHash sh=new SimpleHash("MD5",entity.getPassword(),salt,1);
        String hashedPassword=sh.toHex();
        entity.setSalt(salt);
        entity.setPassword(hashedPassword);
        int rows=sysUserDao.insertObject(entity);
        sysUserRoleDao.insertObjects(entity.getId(),roleIds);
        return rows;
    }

    @Override
    public Map<String,Object> findById(Integer id){
        SysUser user=sysUserDao.findById(id);
        if(user==null)
            throw new ServiceException("此用户可能已经不存在");
        List<Integer> roleIds=sysUserRoleDao.findRoleIdsByUserId(id);
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("user",user);//这里的key不能随意写,要与客户端取值方式一致
        map.put("roleIds",roleIds);
        return map;


        }


}
















